#!/bin/sh

# 获取系统名称
system_name=$(uname)
# 参数解析
debug_mode="false"
yes_all="false"
user_input=""


# 定义系统提示
systemPrompt="\
# 功能\n \
把自然描述的语言转化成 ${system_name} shell command\n \
# 返回格式\n \
用json返回\n \
属性 success : 布尔型\n \
属性 command : 有效的 ${system_name} shell command\n \
属性 msg : 如果生成command 有误，错误原因写在这里，错误原因尽量使用中文\n \
"

# 生成 Shell 命令函数
generate_shell_command() {
    local userPrompt=$1

    curlData='{
            "model": "deepseek-coder",
            "messages": [
                {"role": "system", "content": "'"${systemPrompt}"'"},
                {"role": "user", "content": "'"${userPrompt}"'"}
            ],
            "response_format": {
                "type": "json_object"
            }
        }'
    printf "%s" "${curlData}"
}


# 调用 ai 平台
call_ai() {
    local api_key=$1
    local api_url=$2
    local curlData=$3

    # 使用环境变量配置API地址
    api_url="${DEEPSEEK_CHAT_API_URL:-https://api.deepseek.com/v1/chat/completions}"

    # 使用 curl 发送请求
    response=$(curl -s -X POST "$api_url" \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer ${api_key}" \
        -d "${curlData}"

    )

    printf "%s"  "$response"
}

# 执行命令函数
execute_command() {
    local command=$1
    echo "Command: ${command}"
    if [ "$yes_all" = "true" ]; then
        eval "$command"
    else
        read -p "Execute? (y/n): " confirm
        if [[ "$confirm" == "y" || "$confirm" == "Y" ]]; then
            eval "$command"
        fi
    fi

}

# 显示使用帮助
show_usage() {
    echo  "Usage: $0 [-h] [-d] [-y] <natural language command>"
    echo  "Options:"
    echo  "  -h  Help"
    echo  "  -d  Debug mode"
    echo  "  -y  Yes to all"
    exit 1
}


### 执行主体部分

# 检查 OPENAI_API_KEY 环境变量
[ -z "${OPENAI_API_KEY}" ] && {
    echo  "Error: Missing OPENAI_API_KEY, please set it using:"
    echo  "  export OPENAI_API_KEY='your-api-key'"
    exit 1
}

# 检查 OPENAI_API_KEY 环境变量
if [[ -z "${OPENAI_API_KEY}" ]]; then
    echo  "Error: Missing OPENAI_API_KEY, please set it using  export OPENAI_API_KEY='your-api-key'"
    exit 1
fi



# 解析选项参数
while [ $# -gt 0 ]; do
    case "$1" in
        -h) show_usage & exit ;;
        -d) debug_mode="true" ;;
        -y) yes_all="true" ;;
        -dy|-yd)
            debug_mode="true"
            yes_all="true"
            ;;
        -*)
            echo "Invalid option: $1"
            show_usage
            ;;
        *) 
            # 捕获剩余参数作为自然语言输入
            user_input="$*"
            break
            ;;
    esac
    shift
done

# 校验自然语言输入
[ -z "$user_input" ] && {
    show_usage
    exit
}


# Debug模式输出解析结果
[ "$debug_mode" = "true" ] && {
    echo  "=======    命令参数   ======="
    printf "%s\n"  "debug_mode: $debug_mode"
    printf "%s\n"  "yes_all: $yes_all"
    printf "%s\n"  "user_input: $user_input"
    echo  "==========================="
    echo  ""
}


# 使用环境变量配置API地址
api_url="${DEEPSEEK_CHAT_API_URL:-https://api.deepseek.com/v1/chat/completions}"

# 生成请求内容
curlData=$(generate_shell_command "${user_input}")

# Debug模式输出请求内容
[ "$debug_mode" = "true" ] && {
    echo  "======= 调用AI平台 ======="
    printf "%s\n"  "api_url: ${api_url}"
    printf "%s\n"  "api_key: ${OPENAI_API_KEY}"
    printf "%s\n"  "data_body: ${curlData}"
    echo  "================================="
    echo  ""
}

# 调用AI平台
response=$(call_ai "${OPENAI_API_KEY}" "${api_url}" "${curlData}")

# Debug模式输出响应内容
[ "$debug_mode" = "true" ] && {
    echo  "======= AI平台返回 ======="
    printf "%s\n"  "$response"
    echo  "============================="
    echo  ""
}

# 提取 JSON 字段（不依赖 jq）
# 1. 提取 content 字段（处理多层转义）
content=$(
    printf "%s"  "$response" | 
    grep -o '"content":.*}"},' |          # 提取 content 字段内容
    sed 's/^"content":[ ]*"//;s/"},$//' | # 去除前后修饰
    sed 's/\\\"/"/g' |                # 转换转义双引号
    sed 's/\\\\/\\/g' |               # 转换转义反斜杠
    sed 's/\\n//g'                    # 去除换行符
)

# 2. 解析内部JSON非字符串字段
parse_value_success() {
  printf "%s"  "$1" | 
  grep -o "\"success\":[^,}]*" |        # 提取目标字段
  cut -d: -f2- |                    # 移除键名
  sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | # 去除首尾空格
  sed 's/^"//;s/"$//'               # 去除包裹的引号
}

# 2. 解析内部JSON字符串字段
parse_value_command() {
  printf "%s"  "$1" | 
  grep -oE "\"command\":.*?\"," |        # 提取目标字段
  cut -d: -f2- |                    # 移除键名
  sed 's/,$//'  |            # 去除包裹的引号
  sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | # 去除首尾空格
  sed 's/^"//;s/"$//'               # 去除包裹的引号
}

# 2. 解析内部JSON字符串字段
parse_value_msg() {
  printf "%s"  "$1" | 
  grep -oE "\"msg\":.*?\"}" |        # 提取目标字段
  cut -d: -f2- |                    # 移除键名
  sed 's/}$//'  |             # 去除包裹的引号
  sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | # 去除首尾空格
  sed 's/^"//;s/"$//'               # 去除包裹的引号
}

success=$(parse_value_success "$content" | tr '[:upper:]' '[:lower:]')
command=$(parse_value_command "$content")
msg=$(parse_value_msg "$content")

# Debug模式输出解析结果
[ "$debug_mode" = "true" ] && {
    echo  "=======   数据解析   ======="
    printf "%s\n"  "Content: $content"
    printf "%s\n"  "Success: $success"
    printf "%s\n"  "Command: $command"
    printf "%s\n"  "Message: $msg"
    echo  "==========================="
    echo  ""
}

# 检查 success 字段
if [[ "$success" == "true" ]]; then
    if [[ -n "$command" ]]; then
        execute_command "$command"
    else
        printf "%s"  "Error: Command not found in response."
        exit 1
    fi
else
    if [[ -n "$msg" ]]; then
        printf "%s"  "Error: $msg"
    else
        printf "%s"  "Error: Unknown error occurred."
    fi
    exit 1
fi